/**
 * @file   FastaHandler.cpp
 * @author Scanagatta Mauro - Alberto Franco
 *
 * Contains the implementation of the class to handle FASTA format.
 */
#include "FastaHandler.h"

#include <sstream>

namespace Biopool
{

void FastaHandler::readFasta(std::vector<FastaHandler::FastaPair>& sequences, std::string filename) 
{
    using namespace std;
    // Some variable declaration
    ifstream inData(filename.c_str());
    char     sequence[256];
    // Check file opening
    if (!inData) 
        throw "Error, could not find FASTA file";
    // Read first line
    inData.getline(sequence, 256, '\n');
    // Go down to the whole file.
    while(!inData.eof())
    {
        // New string to push
        if (sequence[0] == '>')
        {
            FastaHandler::FastaPair newPair;
            newPair.name = string(sequence);
            sequences.push_back(newPair);
        }
        else // No new string. Attach to the old one
        {
            for (int i = 0; i < 256 &&  sequence[i] != 0; i++)
                sequences.back().sequence.push_back(sequence[i]);
        }
        inData.getline(sequence, 256, '\n');
    }
    inData.close();
}

/// Write to string the fasta pairs given.
std::string FastaHandler::writeFasta(std::vector<FastaHandler::FastaPair>& sequences)
{
    using namespace std;
    stringstream outData;
    
    for (size_t i = 0; i < sequences.size(); i++)
    {
        outData << ">" << sequences[i].name << endl;
        for (size_t j = 0; j < sequences[i].sequence.size(); j++)
        {
            outData << sequences[i].sequence[j];
            if ((j + 1) % 80 == 0) outData << endl;
        }
        outData << endl;
    }
    return outData.str();
}

/// Return strings from fasta pairs
std::vector<std::string> FastaHandler::vectorFromFasta(std::vector<FastaHandler::FastaPair>& sequences)
{
    using namespace std;
    vector<string> res;
    for (size_t i = 0; i < sequences.size(); i++)
        res.push_back(sequences[i].sequence);
        
    return res;
}

/// Return the fasta file from string 
std::vector<FastaHandler::FastaPair> FastaHandler::vectorToFasta(std::vector<std::string>& sequences)
{
    using namespace std;
    vector<FastaHandler::FastaPair> res;
    string seq = "Sequence #";
    for (size_t i = 0; i < sequences.size(); i++)
    {
        FastaHandler::FastaPair newpair;
        stringstream ss; ss << i;
        newpair.name     = seq + ss.str();
        newpair.sequence = sequences[i];
        res.push_back(newpair);
    }   
    return res;
}


} // namespace Biopool

